import os
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image

# 创建主窗口
root = tk.Tk()
root.title("批量图片格式转换工具")
root.geometry("400x400")

# 存储选择的文件路径
selected_files = []

# 选择图片文件
def select_files():
    global selected_files
    files = filedialog.askopenfilenames(
        title="选择图片文件",
        filetypes=[("图片文件", "*.png;*.jpg;*.jpeg;*.bmp;*.gif;*.webp")]
    )
    selected_files = list(files)
    if selected_files:
        files_label.config(text=f"已选择 {len(selected_files)} 个文件")

# 选择输出目录
def select_output_dir():
    output_dir = filedialog.askdirectory(title="选择输出目录")
    output_dir_entry.delete(0, tk.END)
    output_dir_entry.insert(0, output_dir)

# 格式转换
def convert_images():
    output_dir = output_dir_entry.get()
    target_format = format_var.get()

    if not selected_files:
        messagebox.showwarning("警告", "请先选择图片文件！")
        return

    if not output_dir:
        messagebox.showwarning("警告", "请选择输出目录！")
        return

    for file in selected_files:
        try:
            img = Image.open(file)
            filename, _ = os.path.splitext(os.path.basename(file))
            output_path = os.path.join(output_dir, f"{filename}.{target_format}")
            img.save(output_path, target_format.upper())
        except Exception as e:
            messagebox.showerror("错误", f"转换文件 {file} 时出错：{e}")
            return

    messagebox.showinfo("完成", "图片格式转换成功！")

# 文件选择按钮
select_files_btn = tk.Button(root, text="选择图片文件", command=select_files)
select_files_btn.pack(pady=10)

# 显示已选文件的标签
files_label = tk.Label(root, text="未选择文件")
files_label.pack()

# 输出目录选择
output_dir_label = tk.Label(root, text="输出目录：")
output_dir_label.pack(pady=5)
output_dir_entry = tk.Entry(root, width=40)
output_dir_entry.pack(pady=5)
output_dir_btn = tk.Button(root, text="选择输出目录", command=select_output_dir)
output_dir_btn.pack(pady=5)

# 格式选择
format_label = tk.Label(root, text="目标格式：")
format_label.pack(pady=5)
format_var = tk.StringVar(value="png")
format_menu = tk.OptionMenu(root, format_var, "png", "jpg", "bmp", "gif")
format_menu.pack(pady=5)

# 转换按钮
convert_btn = tk.Button(root, text="转换格式", command=convert_images)
convert_btn.pack(pady=20)

# 启动主循环
root.mainloop()
